package org.execute.tool.adsPower;

import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdspowerStart2 {
    private final AdspowerClient client;
    private final AdspowerBrowserManager manager;
    private final List<String> profileIds;
    // 创建限流器，限制为每秒1个许可
    private final RateLimiter rateLimiter = RateLimiter.create(1.0);
    // 构造方法：初始化API密钥和批量配置ID列表
    public AdspowerStart2(String apiKey, List<String> profileIds) {
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new IllegalArgumentException("API密钥不能为空");
        }
        client = new AdspowerClient(apiKey);
        manager = new AdspowerBrowserManager(client);
        this.profileIds = profileIds;
    }

    //    一个方法， 批量打开浏览器
    public Map<String, AdsPowerWebAction> openBrowserList() {
        Map<String, AdsPowerWebAction> map = new HashMap<String, AdsPowerWebAction>();


        Map<String, Map<String, Object>> launchResults = manager.startBrowserList(profileIds);
        for (String profileId : profileIds) {
            Map<String, Object> stringObjectMap = launchResults.get(profileId);
            JSONObject jsonData = new JSONObject(stringObjectMap);
            // 配置WebDriver
            System.setProperty("webdriver.chrome.driver", jsonData.getJSONObject("data").getString("webdriver"));
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption(
                    "debuggerAddress",
                    jsonData.getJSONObject("data").getJSONObject("ws").getString("selenium")
            );
            WebDriver driver = new ChromeDriver(options);
            AdsPowerWebAction webAction = new AdsPowerWebAction(driver);
            map.put(profileId, webAction);
        }
        return map;
    }
    public AdsPowerWebAction openBrowser(String profileId) throws IOException {
        // 每次调用前先获取许可，确保不超过每秒一次的限制
        rateLimiter.acquire();

        Map<String, Object> launchResults = manager.startBrowser(profileId);

        JSONObject jsonData = new JSONObject(launchResults);
        System.out.println("浏览器打开结果："+profileId+"   "+JSONObject.toJSON(jsonData));
        // 配置WebDriver
        System.setProperty("webdriver.chrome.driver", jsonData.getJSONObject("data").getString("webdriver"));
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption(
                "debuggerAddress",
                jsonData.getJSONObject("data").getJSONObject("ws").getString("selenium")
        );
        WebDriver driver = new ChromeDriver(options);

        return new AdsPowerWebAction(driver);
    }


    void closeAll() {
        closeAllBrowsers(manager);
        try {
            client.close(); // 最后关闭连接池
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 关闭所有浏览器（使用传入的manager，确保client未关闭）
     */
    private void closeAllBrowsers(AdspowerBrowserManager manager) {
        if (manager == null) return;

        for (String profileId : profileIds) {
            try {
                manager.stopBrowser(profileId); // 此时client仍未关闭，可正常发送请求
                System.out.println("[" + profileId + "] 浏览器已关闭");
            } catch (IOException e) {
                System.err.println("[" + profileId + "] 关闭失败: " + e.getMessage());
            }
        }
    }


    public void stopBrowser(String profileId) throws IOException {
        manager.stopBrowser(profileId); // 此时client仍未关闭，可正常发送请求
    }
}
